#!/bin/bash
#
# Compiles code with DDC and runs the resulting code in node.js.
#
# The first script supplied should be the one with `main()`.
#
# Saves the output in the same directory as the sources for convenient
# inspection, modification or rerunning the code.
set -e

function follow_links() {
  file="$1"
  while [ -h "$file" ]; do
    file="$(readlink "$file")"
  done
  echo "$file"
}
PROG_NAME="$(follow_links "$BASH_SOURCE")"
SDK_DIR="$( cd "${PROG_NAME%/*}/../../.."; pwd -P)"

if [[ `uname` == 'Darwin' ]];
then
  OUT_DIR="$SDK_DIR"/xcodebuild
else
  OUT_DIR="$SDK_DIR"/out
fi

if [ -z "$DART_CONFIGURATION" ];
then
  DIRS=$( ls "$OUT_DIR" )
  # list of possible configurations in decreasing desirability
  CONFIGS=("ReleaseX64" "ReleaseIA32" "DebugX64" "DebugIA32"
    "ReleaseARM"    "ReleaseARM64"    "ReleaseARMV5TE"
    "DebugARM"      "DebugARM64"      "DebugARMV5TE")
  DART_CONFIGURATION="None"
  for CONFIG in ${CONFIGS[*]}
  do
    for DIR in $DIRS;
    do
      if [ "$CONFIG" = "$DIR" ];
      then
        # choose most desirable configuration that is available and break
        DART_CONFIGURATION="$DIR"
        break 2
      fi
    done
  done
  if [ "$DART_CONFIGURATION" = "None" ]
  then
    echo "No valid dart configuration found in $OUT_DIR"
    exit 1
  fi
fi

GEN_DIR="$OUT_DIR"/"$DART_CONFIGURATION"/gen/utils/dartdevc

KERNEL=false
if [ "$1" = "-k" ]; then
  KERNEL=true
  shift
fi

BASENAME=$( basename "${1%.*}")
LIBROOT=$(cd $( dirname "${1%.*}") && pwd)

if [ "$KERNEL" = true ]; then

  if [ ! -e $GEN_DIR/kernel/ddc_sdk.dill ]; then
    echo "DDC SDK must be built first, please run:"
    echo "    pushd $SDKDIR"
    echo "    ./tools/build.py -m release dartdevc_kernel_sdk"
    exit 1
  fi

  NODE_PATH=$GEN_DIR/kernel/common:$LIBROOT:$NODE_PATH

  $SDK_DIR/sdk/bin/dartdevc --kernel --modules=node \
      --dart-sdk-summary=$GEN_DIR/ddc_sdk.sum \
      -o $LIBROOT/$BASENAME.js $*
else

  if [ ! -e $GEN_DIR/ddc_sdk.sum ]; then
    echo "DDC SDK must be built first, please run:"
    echo "    pushd $SDKDIR"
    echo "    ./tools/build.py -m release dartdevc_sdk"
    exit 1
  fi

  NODE_PATH=$GEN_DIR/js/common:$LIBROOT:$NODE_PATH

  $SDK_DIR/sdk/bin/dartdevc --modules=node \
      --library-root=$LIBROOT --dart-sdk-summary=$GEN_DIR/ddc_sdk.sum \
      -o $LIBROOT/$BASENAME.js $*
fi

export NODE_PATH
pushd $LIBROOT > /dev/null
# TODO(jmesserly): we could have this output the same content as the devtool
# script, so you could debug the output without recompiling?
echo "
    let source_maps;
    try {
      source_maps = require('source-map-support');
      source_maps.install();
    } catch(e) {
    }
    let sdk = require(\"dart_sdk\");
    let main = require(\"./$BASENAME\").$BASENAME.main;
    sdk.dart.ignoreWhitelistedErrors(false);
    try {
      sdk._isolate_helper.startRootIsolate(main, []);
    } catch(e) {
      if (!source_maps) {
        console.log('For Dart source maps: npm install source-map-support');
      }
      console.error(e);
      process.exit(1);
    }" \
    > $LIBROOT/$BASENAME.run.js
node $BASENAME.run.js || exit 1
popd > /dev/null
